package com.ruoyi.pos.service.impl.member;

import com.ruoyi.pos.domain.member.PosMember;
import com.ruoyi.pos.domain.dto.member.request.MemberQueryRequest;
import com.ruoyi.pos.domain.dto.member.response.MemberResponse;
import com.ruoyi.pos.domain.dto.common.response.BasePageResponse;
import com.ruoyi.pos.mapper.member.PosMemberMapper;
import com.ruoyi.pos.service.member.IPosMemberService;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * POS会员Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-01-30
 */
@Service
@Transactional(transactionManager = "memberTransactionManager")
public class PosMemberServiceImpl implements IPosMemberService {

    @Autowired
    private PosMemberMapper posMemberMapper;

    /**
     * 查询单个会员信息
     * 支持根据ID、编码、手机号查询
     * 
     * @param request 查询请求
     * @return 会员信息
     */
    @Override
    public MemberResponse getMember(MemberQueryRequest request) {
        PosMember member = null;
        
        if (request.getMemberId() != null) {
            member = posMemberMapper.selectPosMemberById(request.getMemberId());
        } else if (StringUtils.isNotEmpty(request.getMemberCode())) {
            member = posMemberMapper.selectPosMemberByPhoneOrCode(request.getMemberCode(), null);
        } else if (StringUtils.isNotEmpty(request.getPhone())) {
            member = posMemberMapper.selectPosMemberByPhoneOrCode(null, request.getPhone());
        }
        
        if (member == null) {
            return null;
        }
        
        return convertToResponse(member);
    }

    /**
     * 分页查询会员列表
     * 
     * @param request 查询请求
     * @return 分页响应
     */
    @Override
    public BasePageResponse<MemberResponse> queryMembers(MemberQueryRequest request) {
        PosMember member = new PosMember();
        member.setMemberId(request.getMemberId());
        member.setMemberNo(request.getMemberCode());
        member.setPhoneNumber(request.getPhone());
        member.setMemberName(request.getMemberName());
        member.setMemberStatus(request.getMemberStatus());
        
        List<PosMember> members = posMemberMapper.selectPosMemberList(member);
        List<MemberResponse> responses = members.stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
        
        return new BasePageResponse<>(responses, members.size());
    }

    /**
     * 转换实体为响应DTO
     * 
     * @param member 会员实体
     * @return 会员响应DTO
     */
    private MemberResponse convertToResponse(PosMember member) {
        MemberResponse response = new MemberResponse();
        BeanUtils.copyBeanProp(response, member);
        return response;
    }
}
